package com.tau.egonetwork.facebook;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.json.JSONObject;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.exceptions.FacebookAccessTokenException;
import com.tau.egonetwork.exceptions.FacebookException;
import com.tau.egonetwork.net.IExceptionHandler;

public class FacebookExceptionHandler implements IExceptionHandler {

	private static final String FACEBOOK_ERROR_CODE = "errorCode";
	private static final String FACEBOOK_ERROR_TYPE = "message";
	private static final String FACEBOOK_ERROR_OAUTH = "OAuthException";

	@Override
	public void onException(Exception e, InputStream errorStream)
			throws Exception {
		
		if (errorStream != null) {
			
			BufferedReader readError = new BufferedReader(
			        new InputStreamReader(errorStream));
			String error;
			StringBuffer buffer = new StringBuffer();
	 
			while ((error = readError.readLine()) != null) {
				buffer.append(error);
			}
			readError.close();
												
			JSONObject json = null;
			try {
				json = new JSONObject(buffer.toString());
			} catch (Exception ex) {
				throw new FacebookException(e);
			}
						
			if (json.has(FACEBOOK_ERROR_CODE)) {
				if (json.has(FACEBOOK_ERROR_TYPE)) {
					if (json.getString(FACEBOOK_ERROR_TYPE).equals(FACEBOOK_ERROR_OAUTH)) {
						throw new FacebookAccessTokenException(e);
					}
				}
			}
		}
		
		//if we got to here without throwing anything more specific:
		Log.writeExceptionToLog(e);
		throw new FacebookException(e);
		
	}

}
